package com.example.demo.redis;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
public class RedisUtil {
    //这里 命名不可以是redisTemplate @Resource 会根据变量名自动注入Bean
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void put(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    public Boolean isExist(String key) {
        return stringRedisTemplate.hasKey(key);
    }

    public boolean setNx(String key, String value) {
        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(key, value));
    }

    public Long exeLua(String lua, String key) {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(lua, Long.class);
        return stringRedisTemplate.execute(redisScript, Collections.singletonList(key));
    }

    public void del(String key) {
        stringRedisTemplate.delete(key);
    }
}
